<?php


function returnData($code,$msg,$data=''){
    return json_encode([
        'code'=>$code,
        'msg'=>$msg,
        'data'=>$data
    ]);
}

/**
 * 删除数组中没有子数组的元素
 * @param $array 二维数组
 * @param $field 子数组索引名
 * @return array
 */

function unsetArrayNotSonArray($array,$field){

    foreach ($array as $k=>$v){

        if(!isset($v[$field])){

            unset($array[$k]);
        }

    }

    return $array;
}


/**
 * 返回数组中指定的一列
 * @param $input            需要取出数组列的多维数组（或结果集）
 * @param $columnKey        需要返回值的列，它可以是索引数组的列索引，或者是关联数组的列的键。 也可以是NULL，此时将返回整个数组（配合index_key参数来重置数组键的时候，非常管用）
 * @param null $indexKey    作为返回数组的索引/键的列，它可以是该列的整数索引，或者字符串键值。
 * @return array            返回值
 */
function _array_column($input, $columnKey, $indexKey = null)
{
    if (!function_exists('array_column')) {
        $columnKeyIsNumber = (is_numeric($columnKey)) ? true : false;
        $indexKeyIsNull = (is_null($indexKey)) ? true : false;
        $indexKeyIsNumber = (is_numeric($indexKey)) ? true : false;
        $result = array();
        foreach ((array)$input as $key => $row) {
            if ($columnKeyIsNumber) {
                $tmp = array_slice($row, $columnKey, 1);
                $tmp = (is_array($tmp) && !empty($tmp)) ? current($tmp) : null;
            } else {
                $tmp = isset($row[$columnKey]) ? $row[$columnKey] : null;
            }
            if (!$indexKeyIsNull) {
                if ($indexKeyIsNumber) {
                    $key = array_slice($row, $indexKey, 1);
                    $key = (is_array($key) && !empty($key)) ? current($key) : null;
                    $key = is_null($key) ? 0 : $key;
                } else {
                    $key = isset($row[$indexKey]) ? $row[$indexKey] : 0;
                }
            }
            $result[$key] = $tmp;
        }
        return $result;
    } else {
        return array_column($input, $columnKey, $indexKey);
    }
}

/**
 * 获取指定团组下的id集合
 * @param teamId
 * @return array
 */
 function getDownIdToTeamId($teamId,$teamList){

    $down  = getDownLevel($teamList,$teamId,'team_id','team_pid');

    array_push($down,$teamId);

    return $down;

}

/**
 * 获取无限极分类所有下级ID
 * @param $data 无限极列表
 * @param $selfLevel 本级id
 * @param $idField  主键字段
 * @param $pidField 上级字段
 * @return array  一维数组id集合
 */
 function getDownLevel($data,$selfLevel,$idField,$pidField,$level=1){

    static $downArray = [];
    if($level == 1){
        $downArray = [];
    }
    foreach ($data as $k=> $v){

        if($v[$pidField] == $selfLevel ){
            $selfPid = $v[$idField];
            $downArray[] = $v[$idField];
            $level++;
            getDownLevel($data,$selfPid,$idField,$pidField,$level);
        }
    }

    $arr = $downArray;


    return $arr;

}




//curl请求
//$url 参数默认是自带参
function curl($URI, $params = false){

    $ch=curl_init();
    curl_setopt($ch,CURLOPT_URL, $URI);
    curl_setopt($ch, CURLOPT_NOSIGNAL, true);
    curl_setopt($ch, CURLOPT_TIMEOUT_MS, 500);
    if($params){
        curl_setopt($ch,CURLOPT_POST,true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
    }
    curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
    curl_setopt($ch, CURLOPT_SSLVERSION, 3);


    $strRes=curl_exec($ch);

    ////var_dump($strRes);
    curl_close($ch);
    return $strRes;
}


//父子关系数组整合 == 特殊情况
function fatherSonArray1($sonArr,$fatherArr,$sonkey,$fatherkey,$newkey,$del,$del1){
    //$sonArr 子数组
    //$fatherArr 父数组
    //$son 子数组键名
    //$father 父数组键名
    //$newkey 整合过的新键名
    foreach ($fatherArr as $key => $value) {
        $fatherArr[$key][$newkey]  = '';
        foreach ($sonArr as $k => $v) {

            if($v[$sonkey] == $value[$fatherkey]){
                unset($v[$del]);
                unset($v[$del1]);

                $fatherArr[$key][$newkey][]  = $v; //['creditimg_path'];
                $fatherArr[$key]['id']  = 0;
                unset($fatherArr[$key][$del1]);

            }
        }

    }

    return $fatherArr;
}


//父子关系数组整合 ===原
function fatherSonArray($sonArr,$fatherArr,$sonkey,$fatherkey,$newkey){
    //$sonArr 子数组
    //$fatherArr 父数组
    //$son 子数组键名
    //$father 父数组键名
    //$newkey 整合过的新键名
    foreach ($fatherArr as $key => $value) {
        $fatherArr[$key][$newkey]  = null;
        foreach ($sonArr as $k => $v) {

            if($v[$sonkey] == $value[$fatherkey]){

                $fatherArr[$key][$newkey][]  = $v; //['creditimg_path'];

            }
        }

    }

    return $fatherArr;
}


/**
 * 参数检测
 *
 * @param $post 表单数据
 * @param $paramNames 需要验证的参数
 * @return false|string
 */
function checkParams($post,$paramNames){

    foreach ($post as $key => $value) {

        if(!in_array($key,$paramNames)){

            return returnData(400,'参数名有误'.$key);
        }

        if(empty($value)){

            return returnData(400,'('.$key.')参数值空');

        }
    }
    //检测参数是否缺少
    foreach ($paramNames as $key1 => $value1) {

        if(!isset($post[$value1])){

            return returnData(400,'缺少参数'.$value1);

        }
    }
    return '1';
}




/**
 **base64单图上传储存方法
 **$imgbase64 base64图片数据
 **$path  图片保存的路径
 * type 1已去掉头部信息，2未去掉
 **/
function base64_img($imgbase64,$path,$type=1){
    if($type == 2){

        $basestr = explode(',',$imgbase64);
        $img  = base64_decode($basestr[1]);

    }else{
        $img  = base64_decode($imgbase64);
    }


    //保存图片到指定路径
    if(file_put_contents($path,$img)){

        return true;
    }else{
        return false;
    }


}



/**
 **base64上传储存方法
 **$imgbase64 去头base64图片数据
 **$path  图片保存的路径
 **$type  模式1是已经去掉头信息的 /模式2是未去头信息 图片与图片之间|分割  头信息和数组,分割
 **/
function base64_upload($imgbase64,$path,$type='1'){

    if($type==2){
        if(!is_array($imgbase64)){

            $baseArr = explode('|',$imgbase64);
        }else{
            $baseArr = array_filter($imgbase64);
        }



        $imgbase64 = array();

        foreach ($baseArr as $key => $value) {

            $imgbase64[]= explode(',', $value)[1];


        }
    }


    if(!is_array($imgbase64)){
        $imgbase64 = explode(',', $imgbase64);
    }

    if(is_array($imgbase64) && !empty($imgbase64)){

        foreach ($imgbase64 as $key => $value) {

            $newstr = base64_decode($value);
            $p = './';
            $newpath = $path.date('YmdHis',time()).rand(1001,9999).'.jpg';

            if(file_put_contents($p.$newpath,$newstr)){
                Cut($newpath,750,400);
                $pathArr[$key] = $newpath;


            }
        }



        return $pathArr;
    }
}



/**
 * 无限极递归
 * @param $list  无限极表数据
 * @param string $pk  主键
 * @param string $pid  上级id
 * @param string $child 新key
 * @param int $root
 * @return array
 */
function make_tree($list,$pk='c_id',$pid='c_pid',$child='son',$root=0){
    $tree=array();
    $packData=array();
    foreach ($list as $data) {
//转换为带有主键id的数组
        $packData[$data[$pk]] = $data; //$packData[1]=$data; $packData[2]=$data
    }
    foreach ($packData as $key =>$val){
        if($val[$pid]==$root){ //代表跟节点
            $tree[]= &$packData[$key];
        }else{
//找到其父类
            $packData[$val[$pid]][$child][]= &$packData[$key];
        }
    }
    return $tree;
}


/**
 * 将xml转换为数组
 * @param $xml  需要转化的xml
 * @return mixed
 */
function xml_to_array($xml){
    $ob = simplexml_load_string($xml);
    $json = json_encode($ob);
    $array = json_decode($json, true);
    return $array;
}




/**
 * PHP post请求之发送XML数据
 * @param $url 请求的URL
 * @param $xmlData
 * @return mixed
 */
function xml_post_request($url, $xmlData){
    $header[] = "Content-type: text/xml";        //定义content-type为xml,注意是数组
    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $xmlData);
    $response = curl_exec($ch);
    if (curl_errno($ch)) {
        print curl_error($ch);
    }
    curl_close($ch);
    return $response;
}


/**
 * PHP post请求之发送Json对象数据
 *
 * @param $url 请求url
 * @param $jsonStr 发送的json字符串
 * @return array
 */
function http_post_json($url, $jsonStr)
{
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonStr);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_HTTPHEADER, array(
            'Content-Type: application/json; charset=utf-8',
            'Content-Length: ' . strlen($jsonStr)
        )
    );
    $response = curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);

    return array($httpCode, $response);
}

//冒泡排序（数组排序）
function bubble_sort($array)
{
    $count = count($array);
    if ($count <= 0) return false;

    for($i=0; $i<$count; $i++){
        for($j=$count-1; $j>$i; $j--){
            if ($array[$j] < $array[$j-1]){
                $tmp = $array[$j];
                $array[$j] = $array[$j-1];
                $array[$j-1] = $tmp;
            }
        }
    }
    return $array;
}


/**
 * 获得用户的真实IP地址
 *
 * @access public
 * @return string
 */
function real_ip()
{
    $realip = NULL;

    if ($realip !== NULL)
    {
        return $realip;
    }

    if (isset($_SERVER))
    {
        if (isset($_SERVER['HTTP_X_FORWARDED_FOR']))
        {
            $arr = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);

            /* 取X-Forwarded-For中第一个非unknown的有效IP字符串 */
            foreach ($arr AS $ip)
            {
                $ip = trim($ip);

                if ($ip != 'unknown')
                {
                    $realip = $ip;

                    break;
                }
            }
        }
        elseif (isset($_SERVER['HTTP_CLIENT_IP']))
        {
            $realip = $_SERVER['HTTP_CLIENT_IP'];
        }
        else
        {
            if (isset($_SERVER['REMOTE_ADDR']))
            {
                $realip = $_SERVER['REMOTE_ADDR'];
            }
            else
            {
                $realip = '0.0.0.0';
            }
        }
    }
    else
    {
        if (getenv('HTTP_X_FORWARDED_FOR'))
        {
            $realip = getenv('HTTP_X_FORWARDED_FOR');
        }
        elseif (getenv('HTTP_CLIENT_IP'))
        {
            $realip = getenv('HTTP_CLIENT_IP');
        }
        else { $realip = getenv('REMOTE_ADDR');
        }
    }
    preg_match("/[\d\.]{7,15}/", $realip, $onlineip);
    $realip = !empty($onlineip[0]) ? $onlineip[0] : '0.0.0.0';
    return $realip;
}

/**
 * @uses 根据生日计算年龄，年龄的格式是：2016-09-23
 * @param string $birthday
 * @return string|number
 */
 function calcAge($birthday) {
    $iage = 0;
    if (!empty($birthday)) {
        $year = date('Y',strtotime($birthday));
        $month = date('m',strtotime($birthday));
        $day = date('d',strtotime($birthday));

        $now_year = date('Y');
        $now_month = date('m');
        $now_day = date('d');

        if ($now_year > $year) {
            $iage = $now_year - $year - 1;
            if ($now_month > $month) {
                $iage++;
            } else if ($now_month == $month) {
                if ($now_day >= $day) {
                    $iage++;
                }
            }
        }
    }
    return $iage;
}

/**
 * @uses 根据生日计算年龄，年龄的格式是：2016-09-23
 * @param string $birthday
 * @return string|number 返回是4岁3个月
 */
function calcAge_($birthday) {
    $iage = ['year'=> 0 ,'month'=> 0];
    if (!empty($birthday)) {
        $year = date('Y',strtotime($birthday));
        $month = date('m',strtotime($birthday));

        $now_year = date('Y');
        $now_month = date('m');

        if ($now_year > $year) {
            $iage['year'] = $now_year - $year - 1;
            $iage['month'] = $month;

            if ($now_month > $month) {
                $iage['year']++;
                $iage['month'] = $now_month-$month;
            }

        }else{

            $iage['month'] = ($now_month-$month)?:1;
        }
    }

    return $iage;
}

/**
 * 判断当前服务器系统
 * @return string
 */
function getOS(){
    if (PATH_SEPARATOR == ':') {
        return 'Linux';
    } else {
        return 'Windows';
    }
}


//获取用户ip地址
function getIPaddress(){
    $unknown = 'unknown';
    if ( isset($_SERVER['HTTP_X_FORWARDED_FOR']) && $_SERVER['HTTP_X_FORWARDED_FOR'] && strcasecmp($_SERVER['HTTP_X_FORWARDED_FOR'], $unknown) ) {
        $ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
    } else if ( isset($_SERVER['REMOTE_ADDR']) && $_SERVER['REMOTE_ADDR'] && strcasecmp($_SERVER['REMOTE_ADDR'], $unknown) ) {
        $ip = $_SERVER['REMOTE_ADDR'];
    }
    /*
    处理多层代理的情况
    或者使用正则方式：$ip = preg_match("/[\d\.]{7,15}/", $ip, $matches) ? $matches[0] : $unknown;
    */
    if (false !== strpos($ip, ','))
        $ip = reset(explode(',', $ip));
    return $ip;


}

//时间轴
function tranTime($time) {
    date_default_timezone_set("PRC");
    $rtime = date("m-d H:i",$time);
    $htime = date("H:i",$time);
    $ymd=date('Y-m-d H:i:s',$time);

    $time = time() - $time;

    if ($time < 60) {
        $str = '刚刚';
    }
    elseif ($time < 60 * 60) {
        $min = floor($time/60);
        $str = $min.'分钟前';
    }
    elseif ($time < 60 * 60 * 24) {
        $h = floor($time/(60*60));
        $str = $h.'小时前 '.$htime;
    }
    elseif ($time < 60 * 60 * 24 * 3) {
        $d = floor($time/(60*60*24));
        if($d==1)
            $str = '昨天 '.$rtime;
        else
            $str = '前天 '.$rtime;
    }
    else {
        $str = $ymd;
    }
    return $str;
}



/**
 * 计算指定经纬度附近5公里
 * @lng 当前的经纬
 * @lat 当前纬度
 * @distance 附近公里数
 */
function returnSquarePoint($lng, $lat,$distance = 0.5){  //计算经纬度距离
    $earth_radius = 6371;
    $dlng =  2 * asin(sin($distance / (2 * $earth_radius)) / cos(deg2rad($lat)));
    $dlng = rad2deg($dlng);
    $dlat = $distance/$earth_radius;
    $dlat = rad2deg($dlat);
    return array(
        'left-top'=>array('lat'=>$lat + $dlat,'lng'=>$lng-$dlng),
        'right-top'=>array('lat'=>$lat + $dlat, 'lng'=>$lng + $dlng),
        'left-bottom'=>array('lat'=>$lat - $dlat, 'lng'=>$lng - $dlng),
        'right-bottom'=>array('lat'=>$lat - $dlat, 'lng'=>$lng + $dlng)
    );
}



/**
 * 文章匹配url 转成实际连接
 * @str 文章内容
 */

function turnUrl($str){

    preg_match_all('#(http(s)?://)+(.*)(.com)+#U',$str,$match);

    foreach($match[0] as $value){
        $strReplace='<a href=\''.$value.'\'>'.' '.$value.' '."</a>";
        $str=str_replace($strReplace,$value,$str);//文本中存在重复的url 且进行了一次替换的时候把先前的替换回来重新替换一次
        $str=str_replace($value,$strReplace,$str);
    }

    return  $str;
}


/**
 * 文章匹配img src替换掉路径
 */

function updateImgSrc($str){

    return removeUrl($str,"\/public");

}


function removeUrl($str = '',$fil = '')
 {
     $preg = '/<img.*?src=[\"|\']?(.*?)[\"|\']?\s.*?>/i';//匹配img标签的正则表达式
     preg_match_all($preg, $str, $allImg);//这里匹配所有的img
     $count=count($allImg[0]);

     for($i=0;$i<=$count;$i++){
         $str = preg_replace('/(<img.+src=\"?.+)('.$fil.')(.+\.(jpg|jpeg|gif|bmp|bnp|png)\"?.+>)/i',"\${1}\${3}",$str);
     }

     return $str;
 }


//取出文章内的src 放进一个数组新key里
function getImgSrc($array,$key,$newkey){

    foreach ($array as $k=>&$v){

        $pattern="/<[img|IMG].*?src=[\'|\"](.*?(?:[\.gif|\.jpg]))[\'|\"].*?[\/]?>/";
        preg_match_all($pattern,$v[$key],$match);
        $v[$newkey] = isset($match[1][0])?$match[1][0]:'';

    }

    return $array;


}

//算出本周开始到结束日期

function getWeekDay($to_day){

    $sdefaultDate = $to_day;

//$first =1 表示每周星期一为开始日期 0表示每周日为开始日期
    $first=1;

//获取当前周的第几天 周日是 0 周一到周六是 1 - 6
    $w=date('w',strtotime($sdefaultDate));

//获取本周开始日期，如果$w是0，则表示周日，减去 6 天
    $week_start=date('Y-m-d',strtotime("$sdefaultDate -".($w ? $w - $first : 6).' days'));
//本周结束日期
    $week_end=date('Y-m-d',strtotime("$week_start +6 days"));


    return ['start'=>$week_start,'end'=>$week_end];


}

/**
 * 获取上周的开始日期和结束日期
 */
function getLastWeekDay($to_day){
    $date=$to_day;  //当前日期
    $first=1; //$first =1 表示每周星期一为开始日期 0表示每周日为开始日期
    $w=date('w',strtotime($date));  //获取当前周的第几天 周日是 0 周一到周六是 1 - 6
    $now_start=date('Y-m-d',strtotime("$date -".($w ? $w - $first : 6).' days')); //获取本周开始日期，如果$w是0，则表示周日，减去 6 天
    $now_end=date('Y-m-d',strtotime("$now_start +6 days"));  //本周结束日期
    $last_start=date('Y-m-d',strtotime("$now_start - 7 days"));  //上周开始日期
    $last_end=date('Y-m-d',strtotime("$now_start - 1 days"));  //上周结束日期

    return ['start'=>$last_start,'end'=>$last_end];
}

//算两个日期中的每一个日期
function startAndEndDateToDayNum($start,$end){

    $dayNum = (strtotime($end)-strtotime($start))/24/60/60;

    for($i=0;$i<= $dayNum;$i++){

        $dateList[] = date('Y-m-d',strtotime(" +$i day",strtotime($start)));

    }

    return $dateList;

}

//查出来的一周数据,进行对没有记录的天数赋值
/**
 * @param $res  一周的数据
 * @param $dateList  一周的日期
 * @param $key  按哪个字段来重组
 */
function WeekData($res,$dateList,$key){

    foreach ($dateList as $k=>$v){
        $newdata[$k] = 0;
        foreach ($res as $k1=>$v1){
            $d = date('Y-m-d',strtotime($v1[$key]));
            if(in_array($v,$v1)){
                $newdata[$k] = $v1['timelong'];
            }


        }

    }


    return $newdata;


}


//查出来的一周数据,进行对没有记录的天数赋值
/**
 * @param $res  一周的数据
 * @param $dateList  一周的日期
 * @param $key  按哪个字段来重组
 */
function WeekDataForDateIsKey($res,$dateList,$key){

    foreach ($dateList as $k=>$v){
        $newdata[$k] = 0;
        foreach ($res as $k1=>$v1){
            $d = date('Y-m-d',strtotime($v1[$key]));
            if(in_array($v,$v1)){
                $newdata[$k] = $v1['timelong'];
            }


        }

    }


    return $newdata;


}


//算出两个日期之间月份数
function startAndEndDateToMonthNum($start,$end){
    $date1_stamp=strtotime($start);
    $date2_stamp=strtotime($end);
    list($date_1['y'],$date_1['m'])=explode("-",date('Y-m',$date1_stamp));
    list($date_2['y'],$date_2['m'])=explode("-",date('Y-m',$date2_stamp));
    return abs($date_1['y']-$date_2['y'])*12 +$date_2['m']-$date_1['m'];

}


//算出两个日期之间年份集合
function startAndEndDateToYearNum($start,$end){
    $date1_stamp=strtotime($start);
    $date2_stamp=strtotime($end);
    $num = date('Y',$date2_stamp)-date('Y',$date1_stamp);

    for($i=0;$i<=$num;$i++){

       $year[] = date('Y',$date1_stamp)+$i;
    }

    return $year;

}


//计算出前6个月的月份集合
function getMonth($mNum){

    $nowd = date("Y-m-1");
    for ($i=0;$i<=$mNum;$i++){
        $month[] = date('Y-m',strtotime('-'.$i."month $nowd"));
    }

    return $month;
}

/**
 * 算指定日期间相隔多少个月份
 * @param $date1 开始日期
 * @param $date2 结束日期
 * @return number
 */

 function getMonthNum($date1,$date2){
    $date1_stamp=strtotime($date1);
    $date2_stamp=strtotime($date2);
    list($date_1['y'],$date_1['m'])=explode("-",date('Y-m',$date1_stamp));
    list($date_2['y'],$date_2['m'])=explode("-",date('Y-m',$date2_stamp));
    return abs($date_1['y']-$date_2['y'])*12 +$date_2['m']-$date_1['m'];
}


/**
 * 算出指定日期之间每个月的第一天周几，多少天数
 * @param $start  开始日期
 * @param $mnum   多少个月份
 * @return mixed  返回二位数组
 */

 function getDateData($start,$mnum){

    for($i=0;$i<=$mnum;$i++){
        //日期

        $date[$i]['date'] = date("Y-m-d", strtotime("+$i months", strtotime($start)));
        $m = date("m",strtotime($date[$i]['date']));
        $y = date("Y",strtotime($date[$i]['date']));
        //每月的天数
        $date[$i]['daynum'] = cal_days_in_month(CAL_GREGORIAN, $m, $y);
        //每月第一天周几
        $date[$i]['w'] = date('w',strtotime(date("Y-m-01",strtotime($date[$i]['date']))));
        $date[$i]['date'] = date("Y-m", strtotime("+$i months", strtotime($start)));


    }

    return $date;

}

//计算出两个日期之前的所有月份
function DateForMonth($start,$end){

    $num = getMonthNum($start,$end);
    for ($i=0;$i<=$num;$i++){
        $m[] = date('Y-m',strtotime('+'.$i."month $start"));
    }

    return $m;
}


/**
 * 获取用户的设备端类型
 *
 */

function getDevice()
{
    //获取USER AGENT
    $agent = strtolower($_SERVER['HTTP_USER_AGENT']);
    //分析数据
    $is_pc = (strpos($agent, 'windows nt')) ? true : false;
    $is_iphone = (strpos($agent, 'iphone')) ? true : false;
    $is_ipad = (strpos($agent, 'ipad')) ? true : false;
    $is_android = (strpos($agent, 'android')) ? true : false;
    $mac = (strpos($agent, 'mac')) ? true : false;

    //输出数据
    if ($is_pc) {
        return 'PC';
    }
    if ($is_iphone) {
        return "iPhone";
    }
    if ($is_ipad) {
        return "iPad";
    }
    if ($is_android) {
        return "Android";
    }
    if($mac){
        return 'mac';
    }

}


/**
 * 获取浏览器类型
 */
function getBrowser(){
    //获取USER AGENT
    $agent = strtolower($_SERVER['HTTP_USER_AGENT']);
    if (strpos($agent, 'micromessenger')) {
        return 'wx';
    }elseif (strpos($agent, 'qqbrowser')) {
        return 'qq';
    }elseif(strpos($agent, 'chrome')){
        return 'chrome';
    }elseif (strpos($agent, 'firefox')){
        return 'firefox';
    }elseif (strpos($agent, 'ucbrowser')){
        return 'uc';
    }elseif (strpos($agent, 'baiduboxapp')){
        return 'baidu';
    }else{
        return '未检测到浏览器类型';
    }
}

/**
 * 将json写进js文件
 */
function writeFile($array,$path){

    $arr =json_encode($array,JSON_UNESCAPED_UNICODE);

    $res = file_put_contents('.'.$path,"\n".' var $city='. $arr);
    return $res;
}

/**
 * 写入日志
 */
function writeLog($data,$path){
    $res = file_put_contents('.'.$path,'['.date('Y-m-d H:i:s').']：'.var_export($data,true)."\r\n",FILE_APPEND);
    return $res;
}

/**
 * 获取xml文件数据转成数组
 */
function getXmlFileData($url = 'http://101.37.150.196:3131/hqApplet/data/CreateXMLClass.xml'){

    $xml=simplexml_load_string(file_get_contents($url));
    $data = json_decode(json_encode($xml),TRUE);
    return $data;
    
}



/**
 * XML转数组
 * @param unknown $xml
 * @return mixed
 */
function xmlToArray($xml)
{
    //将XML转为array
    $array_data = json_decode(json_encode(simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA)), true);
    return $array_data;
}

/**
 * sockopen 请求
 * @param $url
 * @param array $param
 * @author 品花
 * @date zsdate
 *   #解决fsockopen异步请求失败nginx日志报499问题 fastcgi_ignore_client_abort on;
 */
function sockopenRequest($url, $param=array()){

	$urlinfo = parse_url($url);
	$host = $urlinfo['host'];
	$path = $urlinfo['path'];
	$query = isset($param)? http_build_query($param) : '';

	$port = 80;
	$errno = 0;
	$errstr = '';
	$timeout = 10;

	$fp = fsockopen($host, $port, $errno, $errstr, $timeout);

    if(!$fp){
        return "sockopen 失败";
    }
	$out = "POST ".$path." HTTP/1.1\r\n";
	$out .= "host:".$host."\r\n";
	$out .= "content-length:".strlen($query)."\r\n";
	$out .= "content-type:application/x-www-form-urlencoded\r\n";
	$out .= "connection:close\r\n\r\n";
	$out .= $query;

    fputs($fp, $out);
    $data = fgets($fp,128);
    fclose($fp);
    return  $data;
}

/**
 * 红包算法
 * @param $money 总金额
 * @param $number 红包个数
 * @param $max   单个红包最大上限
 * @param $min   单个红包最小上限
 * @author 品花
 * @date zsdate
 */
function redpacketsArithmetic($money_total,$num,$max,$min){

    if($money_total < $num*0.01) {
        exit('钱太少');
    }

    $rand_arr = array();
    for($i=0; $i<$num; $i++) {
        $rand = rand(1, 100);
        $rand_arr[] = $rand;
    }

    $rand_sum = array_sum($rand_arr);
    $rand_money_arr = array();
    $rand_money_arr = array_pad($rand_money_arr, $num, 0.01);  //保证每个红包至少0.01

    foreach ($rand_arr as $key => $r) {
        $rand_money = number_format($money_total*$r/$rand_sum, 2);

        if($rand_money <= 0.01 || number_format(array_sum($rand_money_arr), 2) >= number_format($money_total, 2)) {
            $rand_money_arr[$key] = 0.01;
        } else {
            $rand_money_arr[$key] = $rand_money;
        }

    }

    $max_index = $max_rand = 0;
    foreach ($rand_money_arr as $key => $rm) {
        if($rm > $max_rand) {
            $max_rand = $rm;
            $max_index = $key;
        }
    }

    unset($rand_money_arr[$max_index]);
    //这里的array_sum($rand_money_arr)一定是小于$money_total的
    $rand_money_arr[$max_index] = number_format($money_total - array_sum($rand_money_arr), 2);

    ksort($rand_money_arr);

     return $rand_money_arr;

}


/**
 * 随机红包
 * @param int $bonus_total  红包总金额
 * @param int $bonus_count 红包个数
 * @param int $bonus_type 红包类型 1=拼手气红包 0=普通红包
 * @return array
 */
function randBonus($bonus_total=0, $bonus_count=3, $bonus_type=1){

    $bonus_items  = array(); // 将要瓜分的结果

    $bonus_balance = $bonus_total; // 每次分完之后的余额

    $bonus_avg   = number_format($bonus_total/$bonus_count, 2); // 平均每个红包多少钱

    $i       = 0;

    while($i<$bonus_count){

        if($i<$bonus_count-1){

            $rand      = $bonus_type?(rand(1, $bonus_balance*100-1)/100):$bonus_avg; // 根据红包类型计算当前红包的金额
            //不能让随机金额大于余额
            while($rand >= $bonus_balance ){
                $rand      = $bonus_type?(rand(1, $bonus_balance*100-1)/100):$bonus_avg;
            }
            $bonus_items[] = sprintf("%.2f",$rand);

            $bonus_balance -= sprintf("%.2f",$rand);

        }else{

            $bonus_items[] = sprintf("%.2f",$bonus_balance) ; // 最后一个红包直接承包最后所有的金额，保证发出的总金额正确

        }

        $i++;

    }

    return $bonus_items;

}

/**
 * 二维数组根据某个值排序
 * @param $list 二维数组
 * @param $field 值字段
 */
function twoArraySort($list,$field,$type=SORT_DESC){

    array_multisort(array_column($list,$field),$type ,$list);

    return $list;
}


/**
 *二维数组分组
 * @param key    根据某个key进行分组
 * @param son   子组key名
 * @param list  二维数组
 * @param groupName  分组key名
 * @return array
 */
function arrayGroup($list,$key,$son,$groupName,$n=""){


    $res =   [];
    foreach($list as $k=>$v){
        $res[$v[$key]][$groupName]   =  $v[$key];
        if($n){
           $res[$v[$key]][$n]   =  $v[$n];
        }

        $res[$v[$key]][$son][]    =   $v;

    }
    $new =[];
    foreach ($res as $k=>&$v){

        $new[] = $v;
    }

    return $new;

}


/**
 * 中心服务获取签名
 * @param $data
 * @param $secret
 * @return string
 * @author 品花
 * @date 2019/4/17 0017 下午 5:51
 */
function getSign($data,$secret,$salt){


    ksort($data);

    $params = http_build_query($data);

    $sign = strtoupper(md5(urldecode($params . $secret .$salt)));

    return $sign;
}



/**
 * 验证签名
 * @param array $data
 * @param string $key
 * @return string
 */

function getVerifySign($data, $key)
{
    $String = formatParameters($data, false);
    //签名步骤二：在string后加入KEY
    $String = $String . "&key=" . $key;
    //签名步骤三：MD5加密
    $String = md5($String);
    //签名步骤四：所有字符转为大写
    $result = strtoupper($String);
    return $result;
}

function formatParameters($paraMap, $urlencode)
{
    $buff = "";
    ksort($paraMap);
    foreach ($paraMap as $k => $v) {
        if($k=="sign"){
            continue;
        }
        if ($urlencode) {
            $v = urlencode($v);
        }
        $buff .= $k . "=" . $v . "&";
    }
    $reqPar = "";
    if (strlen($buff) > 0) {
        $reqPar = substr($buff, 0, strlen($buff) - 1);
    }
    return $reqPar;
}



/**
 * 数组转XMl
 * @param $arr
 * @return string
 * @author 品花
 * @date mydate
 */
 function arrayToXml($arr)
{

    $str='<xml>';
    foreach($arr as $k=>$v) {
        $str.='<'.$k.'>'.$v.'</'.$k.'>';
    }
    $str.='</xml>';
    return $str;

}


/**
 * 求两个日期之间相差的天数
 * (针对1970年1月1日之后，求之前可以采用泰勒公式)
 * @param string $day1
 * @param string $day2
 * @return number
 */
function diffBetweenTwoDays ($day1, $day2)
{
    $second1 = strtotime($day1);
    $second2 = strtotime($day2);

    if ($second1 < $second2) {
    $tmp = $second2;
    $second2 = $second1;
    $second1 = $tmp;
    }
    return ($second1 - $second2) / 86400;
}

/**
 * 获取值较小的随机数
 * @param $min
 * @param $max
 * @return int
 * @author 品花
 * @date 2019/7/17 0017 下午 5:13
 */
function getRand($min,$max) {
    $num=rand($min,$max);
    return rand($min,$num);
}



/**
 * 计算.生肖
 * @param int $year 年份
 * @return str
 */
function get_animal($year){
    $animals = array(
        '鼠', '牛', '虎', '兔', '龙', '蛇',
        '马', '羊', '猴', '鸡', '狗', '猪'
    );
    $key = ($year - 1900) % 12;
    return $animals[$key];
}


/**
 * 计算.星座
 *
 * @param int $month 月份
 * @param int $day 日期
 * @return str
 */
function get_constellation($month, $day){
    $signs = array(
        array('20'=>'宝瓶座'), array('19'=>'双鱼座'),
        array('21'=>'白羊座'), array('20'=>'金牛座'),
        array('21'=>'双子座'), array('22'=>'巨蟹座'),
        array('23'=>'狮子座'), array('23'=>'处女座'),
        array('23'=>'天秤座'), array('24'=>'天蝎座'),
        array('22'=>'射手座'), array('22'=>'摩羯座')
    );
    $key = (int)$month - 1;
    list($startSign, $signName) = each($signs[$key]);
    if( $day < $startSign ){
        $key = $month - 2 < 0 ? $month = 11 : $month -= 2;
        list($startSign, $signName) = each($signs[$key]);
    }
    return $signName;
}


function curl1($param="",$url,$path="") {
    $postUrl = $url;
    $curlPost = $param;
    $cert_path = $path;
    $ch = curl_init();                                      //初始化curl
    curl_setopt($ch, CURLOPT_URL,$postUrl);                 //抓取指定网页
    curl_setopt($ch, CURLOPT_HEADER, 0);                    //设置header
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);            //要求结果为字符串且输出到屏幕上
    curl_setopt($ch, CURLOPT_POST, 1);                      //post提交方式
    curl_setopt($ch, CURLOPT_POSTFIELDS, $curlPost);           // 增加 HTTP Header（头）里的字段
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);        // 终止从服务端进行验证
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);

    curl_setopt($ch,CURLOPT_SSLCERT,$cert_path.'/App/cert/apiclient_cert.pem'); //这个是证书的位置绝对路径
    curl_setopt($ch,CURLOPT_SSLKEY,$cert_path.'/App/cert/apiclient_key.pem'); //这个也是证书的位置绝对路径

    $data = curl_exec($ch);                                 //运行curl
    curl_close($ch);
    return $data;
}




/**
 * 计算某个数字在数组中连续出现次数
 * @param $List
 * @param $number
 * @return int
 */
function consecutiveOccurrences($List,$number){

    $count = 0;
    foreach ($List as  $k => $v){
        if($v == $number &&  $count == 0){

            $count++;
        }
        if(isset($List[$k+1]) && $List[$k+1] == $v && $v==$number){

            $count++;
        }
    }

    return $count;
}


/**
 * 去掉重复值后获取数组长度
 * @param $dataList
 * @return int
 *
 */
function getLenthForUnique($dataList){

    $list = array_unique($dataList);

    return count($list);

}


/**
 * 在一个时间段里获取总秒数和当前流逝秒数
 * @param $inTime    $inTime = [
                                ['start'=> "01:00:30" ,'end'=> "10:00:30"],
                                ['start'=> "12:00:30" ,'end'=> "23:59:30"],
                            ];
 * @return array
 */
function getSumAndPassingForTimePeriod($inTime){


    $now = time();
    $passing = 0;
    $sum  = 0;
    foreach($inTime as $v) {

        $sum += strtotime($v['end']) - strtotime($v['start']);

        if ($now > strtotime($v['end'])) {

            $passing += strtotime($v['end']) - strtotime($v['start']);
        } else {

            $passing += $now - strtotime($v['start']);

        }

    }

    return ['sum'=> $sum ,'passing'=>$passing];
}


/**
 * 根据时间段和间隔获取当前应该属于第几个间隔期
 * @param $inTime //    $inTime = [
                    //        ['start'=> "00:00:10" ,'end'=> "10:00:30"],
                    //        ['start'=> "12:00:00" ,'end'=> "16:59:30"],
                    //        ['start'=> "17:00:30" ,'end'=> "23:59:30"],
                    //    ];
 * @param int $interval
 * @return array
 */
function getCurrentOpenTime($inTime,$interval = 60){


    $now = time();
    $num = 0;
    $time = 0;
    foreach($inTime as $k=> $v) {

        $temp = strtotime($v['end']) - strtotime($v['start']);
        if($now < strtotime($v['end']) ){

            $temp +=$now - strtotime($v['end']);

        }

        $num += $n = intval($temp/$interval);

        if($now- strtotime($v['start']) < $interval ){

            $time = $now -$interval;

        }
        if($now < strtotime($v['end']) ){

            $time = strtotime($v['start'])+$n*$interval;
        }

        if ($now > strtotime($v['start']) && $now < strtotime($v['end'])) {

            break ;
        }

        if(isset($inTime[$k+1])){
            if($now < strtotime($inTime[$k+1]['start']) ){

                $time = strtotime($inTime[$k+1]['start']);
                break ;
            }
        }


    }

    return ['time'=> $time,'date_num'=> $num ];
}





